import { createSlice } from '@reduxjs/toolkit'
import { transData, createJobFilter } from '../components/SmartTable/dataUtils'
import { GROUP_NEW } from '../contants.js'

const jobSlice = createSlice({
  name: 'job',
  initialState: {
    dataList: [],
    dataListFiltered: [],
    selectedRowKeys: [],
    jobDetail: '',
    dataIndex: -1,
    filters: {
      jobName: ''
    },
    group: GROUP_NEW,
    playList: [],
    playIndex: 0
  },
  reducers: {
    putJobList: (state, action) => {
      const { payload } = action
      const dataList = transData(payload)
      const dataListFiltered = dataList.filter(createJobFilter(state.filters))
      return { ...state, dataList, dataListFiltered, selectedRowKeys: [] }
    },
    putJobCategory: (state, action) => {
      const { payload } = action
      const { lid, params } = payload
      console.log('putJobCategory:', payload)
      return {
        ...state,
        dataListFiltered: state.dataListFiltered.map(item => {
          if (item.lid === lid) {
            return { ...item, ...params }
          }
          return item
        }) }
    },
    putPlayList: (state, action) => {
      const { payload } = action
      console.log('putPlayList')
      return { ...state, playList: payload }
    },

    putPlayIndex: (state, action) => {
      const { payload } = action
      console.log('putPlayIndex')

      return { ...state, playIndex: payload }
    },

    rebuildDataListFiltered: (state, action) => {
      const dataList = state.dataList
      const dataListFiltered = dataList.filter(createJobFilter(state.filters))
      return { ...state, dataListFiltered }
    },
    putSelectedRows: (state, action) => {
      const { payload } = action
      console.log('putSelectedRows:', payload)
      return { ...state, selectedRowKeys: payload }
    },
    putJobDetail: (state, action) => {
      const { payload } = action
      console.log('putJobDetail:', payload)
      return { ...state, jobDetail: payload }
    },


    putFilters: (state, action) => {
      const { payload } = action
      console.log('putFilters:', payload)
      return { ...state, filters: {...state.filters, ...payload} }
    },
    putGroup: (state, action) => {
      const { payload } = action
      console.log('putGroup:', payload)
      return { ...state, group: payload }
    }
    
    // incrementByAmount: (state, action) => {
    //   state.value += action.payload
    // }
  }
})

export const { putJobList, putSelectedRows, 
  putJobDetail, putFilters, putGroup, rebuildDataListFiltered, 
  putJobCategory,
  putPlayList,
  putPlayIndex
} = jobSlice.actions

export default jobSlice
